/**
 * @file double.c
 * @author moonfish
 * @brief This program can detect adjacant and identical words in files or terminal
 * @version 0.1
 * @date 2023-04-26
 *
 * @copyright Copyright (c) 2023
 *
 *
 * @usage  % double intro.txt
 *          intro.txt:2: the
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>

int line_num;

static int get_word(FILE *fp, char *buf, int size)
{
    char c;
    c = getc(fp);
    for (; c != EOF && isspace(c); c = getc(fp))
    {
        if (c == '\n')
            line_num++;
    }
    int i = 0;
    for (; c != EOF && !isspace(c); c = getc(fp))
    {
        if (i < size - 1)
            buf[i++] = tolower(c);
    }

    if (i < size)
    {
        buf[i] = '\0';
    }

    if (c != EOF)
        ungetc(c, fp);

    // printf("word: %s\n", buf);
    return buf[0] != '\0';
}

static void double_word(char *file_name, FILE *fp)
{
    char prev[128], word[128];
    line_num = 1;
    prev[0] = '\0';
    while (get_word(fp, word, sizeof(word)))
    {
        if (isalpha(word[0]) && strcmp(prev, word) == 0)
        {
            if (file_name)
            {
                printf("%s: ", file_name);
            }
            printf("%d: %s\n", line_num, word);
        }
        strcpy(prev, word);
    }
    return;
}

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; i++)
    {
        FILE *fp = fopen(argv[i], "r");
        if (fp == NULL)
        {
            fprintf(stderr, "%s : can't open '%s' (%s)\n",
                    argv[0], argv[i], strerror(errno));
            return EXIT_FAILURE;
        }
        else
        {
            double_word(argv[i], fp);
            fclose(fp);
        }
    }
    if (argc == 1)
    {
        double_word(NULL, stdin);
    }
    return EXIT_SUCCESS;
}
